export default class Watcher {
  constructor(vm, expFn, cb) {
    this.vm = vm;
    this.getter = parsePath(expFn);
    this.cb = cb;
    this.value = this.get();
  }

  get() {
    window.target = this;
    let value = this.getter.call(this.vm, this.vm);
    window.target = undefined;
    return value;
  }

  update() {
    const oldValue = this.value;
    this.value = this.get();
    this.cb.call(this.vm, this.value, oldValue);
  }
}

/**
 * 解析字符串的keypath
 * @param {String} path key字符串
 */
const bailRE = /[^\w.$]/;
export function parsePath(path) {
  if (bailRE.test(path)) return;
  const segments = path.split(".");
  return function(obj) {
    for (let i = 0; i < segment.length; i++) {
      if (!obj) {
        return;
      }
      obj = obj[segments[i]];
    }
  };
}